package io.finer.erp.jeecg.bas.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.api.client.util.Maps;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import io.finer.erp.jeecg.bas.dto.TrayPrintDTO;
import io.finer.erp.jeecg.bas.entity.BasCategoryLabel;
import io.finer.erp.jeecg.bas.entity.BasCustomer;
import io.finer.erp.jeecg.bas.entity.BasMaterial;
import io.finer.erp.jeecg.bas.entity.BasMaterialCategory;
import io.finer.erp.jeecg.bas.entity.BasMaterialTemp;
import io.finer.erp.jeecg.bas.entity.ZrkDeliver;
import io.finer.erp.jeecg.bas.entity.ZrkDeliverEntry;
import io.finer.erp.jeecg.bas.service.IBasCategoryLabelService;
import io.finer.erp.jeecg.bas.service.IBasCustomerService;
import io.finer.erp.jeecg.bas.service.IBasMaterialCategoryService;
import io.finer.erp.jeecg.bas.service.IBasMaterialService;
import io.finer.erp.jeecg.bas.service.IBasMaterialTempService;
import io.finer.erp.jeecg.bas.service.IZrkDeliverEntryService;
import io.finer.erp.jeecg.bas.service.IZrkDeliverService;
import io.finer.erp.jeecg.bas.service.IZrkOrderProcessService;
import io.finer.erp.jeecg.bas.service.IZrkQzOrderService;
import io.finer.erp.jeecg.bas.service.IZzShoporderService;
import io.finer.erp.jeecg.bas.vo.ProductDetails;
import io.finer.erp.jeecg.bas.vo.SpecsAndCount;
import io.finer.erp.jeecg.bas.vo.ZrkDeliverPage;
import io.finer.erp.jeecg.stock.entity.StkTray;
import io.finer.erp.jeecg.stock.entity.StkTrayDetail;
import io.finer.erp.jeecg.stock.service.IStkIoBillService;
import io.finer.erp.jeecg.stock.service.IStkTrayDetailService;
import io.finer.erp.jeecg.stock.service.IStkTrayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

 /**
 * @Description: 销售出货单
 * @Author: jeecg-boot
 * @Date:   2020-10-23
 * @Version: V1.0
 */
@Api(tags="销售出货单")
@RestController
@RequestMapping("/bas/zrkDeliver")
@Slf4j
public class ZrkDeliverController {
	@Autowired
	private IZrkDeliverService zrkDeliverService;
	@Autowired
	private IZrkDeliverEntryService zrkDeliverEntryService;
	@Autowired
	private IStkTrayService stkTrayService;
	@Autowired
	private IStkTrayDetailService stkTrayDetailServie;
	@Autowired
	private IBasMaterialService basMaterialService;
	@Autowired
	private IBasMaterialCategoryService basMaterialCategoryService;
	@Autowired
	private IStkIoBillService stkIoBillService;
	@Autowired
	private IBasCustomerService basCustomerService;
	@Autowired
	private IZzShoporderService zzShoporderService;
	@Autowired
	private IZrkOrderProcessService zrkOrderProcessService;
	@Autowired
	private IBasMaterialTempService basMaterialTempService;
	@Autowired
	private IZrkQzOrderService zrkQzOrderService;
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	@Autowired
	private IBasCategoryLabelService labelService;
	
	/**
	 * 分页列表查询
	 *
	 * @param zrkDeliver
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "销售出货单-分页列表查询")
	@ApiOperation(value="销售出货单-分页列表查询", notes="销售出货单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ZrkDeliver zrkDeliver,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ZrkDeliver> queryWrapper = QueryGenerator.initQueryWrapper(zrkDeliver, req.getParameterMap());
		Page<ZrkDeliver> page = new Page<ZrkDeliver>(pageNo, pageSize);
		IPage<ZrkDeliver> pageList = zrkDeliverService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param zrkDeliverPage
	 * @return
	 */
	@AutoLog(value = "销售出货单-添加")
	@ApiOperation(value="销售出货单-添加", notes="销售出货单-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ZrkDeliverPage zrkDeliverPage) {
		ZrkDeliver zrkDeliver = new ZrkDeliver();
		BeanUtils.copyProperties(zrkDeliverPage, zrkDeliver);
		zrkDeliverService.saveMain(zrkDeliver, zrkDeliverPage.getZrkDeliverEntryList());
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param zrkDeliverPage
	 * @return
	 */
	@AutoLog(value = "销售出货单-编辑")
	@ApiOperation(value="销售出货单-编辑", notes="销售出货单-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ZrkDeliverPage zrkDeliverPage) {
		ZrkDeliver zrkDeliver = new ZrkDeliver();
		BeanUtils.copyProperties(zrkDeliverPage, zrkDeliver);
		ZrkDeliver zrkDeliverEntity = zrkDeliverService.getById(zrkDeliver.getId());
		if(zrkDeliverEntity==null) {
			return Result.error("未找到对应数据");
		}
		zrkDeliverService.updateMain(zrkDeliver, zrkDeliverPage.getZrkDeliverEntryList());
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "销售出货单-通过id删除")
	@ApiOperation(value="销售出货单-通过id删除", notes="销售出货单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		zrkDeliverService.delMain(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "销售出货单-批量删除")
	@ApiOperation(value="销售出货单-批量删除", notes="销售出货单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.zrkDeliverService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "销售出货单-通过id查询")
	@ApiOperation(value="销售出货单-通过id查询", notes="销售出货单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		ZrkDeliver zrkDeliver = zrkDeliverService.getById(id);
		if(zrkDeliver==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(zrkDeliver);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "出货单对应出货明细表通过主表ID查询")
	@ApiOperation(value="出货单对应出货明细表主表ID查询", notes="出货单对应出货明细表-通主表ID查询")
	@GetMapping(value = "/queryZrkDeliverEntryByMainId")
	public Result<?> queryZrkDeliverEntryListByMainId(@RequestParam(name="id",required=true) String id) {
		List<ZrkDeliverEntry> zrkDeliverEntryList = zrkDeliverEntryService.selectByMainId(id);
		return Result.ok(zrkDeliverEntryList);
	}
	
	@GetMapping(value = "/printDeliver")
	public Result<?> printDeliver(@RequestParam(name="id",required=true) String id) {
		return zrkDeliverEntryService.printDeliver(id);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param zrkDeliver
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ZrkDeliver zrkDeliver) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<ZrkDeliver> queryWrapper = QueryGenerator.initQueryWrapper(zrkDeliver, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<ZrkDeliver> queryList = zrkDeliverService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<ZrkDeliver> zrkDeliverList = new ArrayList<ZrkDeliver>();
      if(oConvertUtils.isEmpty(selections)) {
          zrkDeliverList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          zrkDeliverList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<ZrkDeliverPage> pageList = new ArrayList<ZrkDeliverPage>();
      for (ZrkDeliver main : zrkDeliverList) {
          ZrkDeliverPage vo = new ZrkDeliverPage();
          BeanUtils.copyProperties(main, vo);
          List<ZrkDeliverEntry> zrkDeliverEntryList = zrkDeliverEntryService.selectByMainId(main.getId());
          vo.setZrkDeliverEntryList(zrkDeliverEntryList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "销售出货单列表");
      mv.addObject(NormalExcelConstants.CLASS, ZrkDeliverPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("销售出货单数据", "导出人:"+sysUser.getRealname(), "销售出货单"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ZrkDeliverPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ZrkDeliverPage.class, params);
              for (ZrkDeliverPage page : list) {
                  ZrkDeliver po = new ZrkDeliver();
                  BeanUtils.copyProperties(page, po);
                  zrkDeliverService.saveMain(po, page.getZrkDeliverEntryList());
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
    }
    
    /**
	 * 查询托盘明细-打印
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "查询托盘明细-打印")
	@ApiOperation(value="查询托盘明细-打印", notes="查询托盘明细-打印")
	@GetMapping(value = "/queryDeliverDataForPrint")
	public Result<TrayPrintDTO> queryDeliverDataForPrint(@RequestParam(name="id",required=true) String id) {
		Result<TrayPrintDTO> result = new Result<>();
		StkTray stkTray = stkTrayService.getById(id);
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(stkTray!=null) {
			//查询出货单信息
//			ZrkDeliver zd=zrkDeliverService.getById(stkTray.getDeliverId());
			TrayPrintDTO tpb = new TrayPrintDTO();
			//查询托盘明细
			List<StkTrayDetail> stdList = stkTrayDetailServie.selectByMainId(stkTray.getId());
			HashSet<String> materialIdSet = Sets.newHashSet();
			if(CollUtil.isNotEmpty(stdList)) {
				for (StkTrayDetail detail : stdList) {
					String materialId = detail.getMaterialId();
					materialIdSet.add(materialId);
				}
			}
			List<BasMaterial> materials = this.basMaterialService.getByIds(materialIdSet);
			HashSet<String> inspectors = Sets.newHashSet();
			if(CollUtil.isNotEmpty(materials)) {
				List<String> codeList = Lists.newArrayList();
				for (BasMaterial basMaterial : materials) {
					codeList.add(basMaterial.getCode());
				}
				List<BasMaterialTemp> tempList = this.basMaterialTempService.getByCodes(codeList);
				Map<String, BasMaterialTemp> tempMap = Maps.newHashMap();
				if(CollUtil.isNotEmpty(tempList)) {
					for (BasMaterialTemp temp : tempList) {
						tempMap.put(temp.getCode(), temp);
						String inspector = temp.getInspector();
						if(StringUtils.isNotBlank(inspector)) {
							String[] strings = StringUtils.split(inspector, ",");
							for(String str : strings) {
								if(StringUtils.isBlank(str) || inspectors.contains(str.trim())) {
									continue;
								}
								inspectors.add(str.trim());
							}
						}
					}
				}
				//生产信息维护
				Map<String, List<BasMaterial>> mateMap = Maps.newLinkedHashMap();
				Map<String, List<BasMaterial>> labelMap = Maps.newLinkedHashMap();
				for (BasMaterial basMaterial : materials) {
					String categoryId = basMaterial.getCategoryId();
					BasMaterialTemp temp = tempMap.get(basMaterial.getCode());
					String labelId = temp.getLabelId();
					if(StringUtils.isNotBlank(labelId)) {
						List<BasMaterial> mateList = labelMap.get(labelId);
						if(null == mateList) {
							mateList = Lists.newLinkedList();
						}
						mateList.add(basMaterial);
						labelMap.put(labelId, mateList);
						continue;
					}
					List<BasMaterial> list = mateMap.get(categoryId);
					if(null == list) {
						list = Lists.newLinkedList();
					}
					list.add(basMaterial);
					mateMap.put(categoryId, list);
				}
				List<ProductDetails> details = Lists.newArrayList();
				HashSet<String> categoryIds = Sets.newHashSet(UUID.randomUUID().toString());
				Map<String, Integer> cateCountMap = Maps.newHashMap();
				for(Map.Entry<String, List<BasMaterial>> entry : mateMap.entrySet()) {
					String key = entry.getKey();
					List<BasMaterial> value = entry.getValue();
					categoryIds.add(key);
					for(BasMaterial material : value) {
						StringBuffer sb = new StringBuffer(key).append("-");
						BigDecimal length = material.getLength() == null ? 
								BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_DOWN) : material.getLength().setScale(2, BigDecimal.ROUND_DOWN);
						BigDecimal width = material.getWidth() == null ? 
								BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_DOWN) : material.getWidth().setScale(2, BigDecimal.ROUND_DOWN);
						sb.append(width.toPlainString()).append("*").append(length.toPlainString());
						sb.append("-").append(material.getViceQuantity().toPlainString());
						String cateCountKey = sb.toString();
						Integer integer = cateCountMap.get(cateCountKey);
						if(integer == null) {
							cateCountMap.put(cateCountKey, Integer.valueOf(1));
						} else {
							cateCountMap.put(cateCountKey, ++integer);
						}
					}
				}
				List<BasMaterialCategory> categoryList = this.basMaterialCategoryService.listByIds(categoryIds);
				if(null == categoryList) {
					categoryList = Lists.newArrayList();
				}
				Map<String, BasMaterialCategory> categoryMap = Maps.newHashMap();
				for (BasMaterialCategory basMaterialCategory : categoryList) {
					categoryMap.put(basMaterialCategory.getId(), basMaterialCategory);
				}
				Map<String, ProductDetails> cateDetailsMap = Maps.newHashMap();
				for(Map.Entry<String, Integer> entry : cateCountMap.entrySet()) {
					String key = entry.getKey();
					Integer value = entry.getValue();
					String[] strings = StringUtils.split(key, "-");
					String categoryId = strings[0];
					String model = strings[1];
					String viceQuantityString = strings[2];
					SpecsAndCount sc = new SpecsAndCount();
					sc.setSpecs(model);
					if(NumberUtil.toBigDecimal(viceQuantityString).compareTo(BigDecimal.ONE) > 0) {
						sc.setCount(StrUtil.builder(viceQuantityString, "*", String.valueOf(value)).toString());
					} else {
						sc.setCount(String.valueOf(value));
					}
					ProductDetails productDetails = cateDetailsMap.get(categoryId);
					if(null == productDetails) {
						BasMaterialCategory category = categoryMap.get(categoryId);
						productDetails = new ProductDetails();
						productDetails.setProductName(category.getName());
						List<SpecsAndCount> list = CollUtil.newArrayList(sc);
						productDetails.setScList(list);
						cateDetailsMap.put(categoryId, productDetails);
						
					} else {
						List<SpecsAndCount> list = productDetails.getScList();
						list.add(sc);
					}
				}
				for(ProductDetails detail : cateDetailsMap.values()) {
					details.add(detail);
				}
				List<String> labelIdList = Lists.newArrayList(UUID.randomUUID().toString());
				Map<String, Integer> labelCountMap = Maps.newHashMap();
				for(Map.Entry<String, List<BasMaterial>> entry : labelMap.entrySet()) {
					String key = entry.getKey();
					labelIdList.add(key);
					List<BasMaterial> value = entry.getValue();
					for (BasMaterial material : value) {
						StringBuffer sb = new StringBuffer(key).append("-");
						BigDecimal length = material.getLength() == null ? 
								BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_DOWN) : material.getLength().setScale(2, BigDecimal.ROUND_DOWN);
						BigDecimal width = material.getWidth() == null ? 
								BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_DOWN) : material.getWidth().setScale(2, BigDecimal.ROUND_DOWN);
						sb.append(width.toPlainString()).append("*").append(length.toPlainString());
						String labelCountKey = sb.toString();
						Integer integer = labelCountMap.get(labelCountKey);
						if(integer == null) {
							labelCountMap.put(labelCountKey, Integer.valueOf(1));
						} else {
							labelCountMap.put(labelCountKey, ++integer);
						}
					}
				}
				List<BasCategoryLabel> labelList = this.labelService.listByIds(labelIdList);
				if(null == labelList) {
					labelList = Lists.newArrayList();
				}
				Map<String, BasCategoryLabel> theLabelMap = Maps.newHashMap();
				for (BasCategoryLabel label : labelList) {
					theLabelMap.put(label.getId(), label);
				}
				Map<String, ProductDetails> labelDetailsMap = Maps.newHashMap();
				for(Map.Entry<String, Integer> entry : labelCountMap.entrySet()) {
					String key = entry.getKey();
					Integer value = entry.getValue();
					String[] strings = StringUtils.split(key, "-");
					String labelId = strings[0];
					String model = strings[1];
					SpecsAndCount sc = new SpecsAndCount();
					sc.setSpecs(model);
					sc.setCount(String.valueOf(value));
					ProductDetails productDetails = labelDetailsMap.get(labelId);
					if(null == productDetails) {
						BasCategoryLabel label = theLabelMap.get(labelId);
						productDetails = new ProductDetails();
						productDetails.setProductName(label.getCategoryLabel());
						List<SpecsAndCount> list = CollUtil.newArrayList(sc);
						productDetails.setScList(list);
						labelDetailsMap.put(labelId, productDetails);
						
					} else {
						List<SpecsAndCount> list = productDetails.getScList();
						list.add(sc);
					}
				}
				for(ProductDetails detail : labelDetailsMap.values()) {
					details.add(detail);
				}
				
				tpb.setPdList(details);
			}
			//生产人员
			String inspectorStr;
			if(inspectors.isEmpty()) {
				inspectorStr = StringUtils.EMPTY;
			} else {
				inspectorStr = CollUtil.join(inspectors, ",");
			}
			tpb.setCz(inspectorStr);
			//查询客户信息
			String customerId = stkTray.getCustomerId();
			BasCustomer cus = basCustomerService.getById(customerId);
			if(null!=cus) {
				tpb.setCustomerName(cus.getName());
			}else {
				tpb.setCustomerName(StringUtils.EMPTY);
			}
			//时间
			tpb.setCreateTime(stkTray.getCreateTime());
			//质检员（取当前用户）
			if(sysUser!=null) {
				LoginUser loginUser = sysBaseAPI.getUserById(sysUser.getId());
				tpb.setZj(loginUser.getWorkNo());
			}
			//总数
			if(CollUtil.isEmpty(stdList)) {
				tpb.setCount(String.valueOf(0));
			} else {
				tpb.setCount(String.valueOf(stdList.size()));
			}
			
//			BigDecimal count=BigDecimal.ZERO;
//			String materialName="";
//			String specs="";
//			List<SpecsAndCount> sacList=Lists.newArrayList();
//			Map<String,List<SpecsAndCount>> specsListMap = Maps.newHashMap();
//			Set<String> set = new HashSet<>();
//			List<String> MaterialIdList=Lists.newArrayList();
//			List<String> userIdList=Lists.newArrayList();
//			Set<String> userSet = new HashSet<>();
//			if(null!=stdList&&stdList.size()>0) {
//				for(StkTrayDetail st:stdList) {
////					//查询物料明细
//					BasMaterial basMaterial=basMaterialService.getById(st.getMaterialId());
//					MaterialIdList.add(st.getMaterialCode());
//					if(null == basMaterial) {
//						System.out.println(st.getMaterialId());
//					}
//					BigDecimal width = basMaterial.getWidth();
//					if(oConvertUtils.isEmpty(width)) {
//						width = BigDecimal.ZERO;
//					}
//					BigDecimal length = basMaterial.getLength();
//					if(oConvertUtils.isEmpty(length)) {
//						length = BigDecimal.ZERO;
//					}
//					specs = width.setScale(2, BigDecimal.ROUND_HALF_UP)+"*"+length.setScale(2, BigDecimal.ROUND_HALF_UP);
//					SpecsAndCount sac = new SpecsAndCount();
//					sac.setCount(st.getMaterialId());
//					sac.setSpecs(specs);
//					sacList.add(sac);
//					set.add(basMaterial.getCategoryId());
//					materialName=basMaterial.getName();
//					count=count.add(new BigDecimal("1"));//统计物料数量
//					//规格只记录一次
//					if(specs.equals("")) {
//						specs=width.setScale(2, BigDecimal.ROUND_HALF_UP)+"*"+length.setScale(2, BigDecimal.ROUND_HALF_UP);
//					}
//				}
//				LambdaQueryWrapper<BasMaterialTemp> queryWrapper = new LambdaQueryWrapper<BasMaterialTemp>();
//				List<BasMaterialTemp> mtList = null;
//				if(MaterialIdList!=null&&MaterialIdList.size()>0) {
//					queryWrapper.in(BasMaterialTemp::getCode, MaterialIdList);
//					mtList = basMaterialTempService.list(queryWrapper);
//				}
//				List<String> mesIdList = Lists.newArrayList();
//				if(mtList!=null&&mtList.size()>0) {
//					for(BasMaterialTemp mt:mtList) {
//						String orderId = mt.getOrderId();
//						if(oConvertUtils.isNotEmpty(orderId)) {
//							mesIdList.add(orderId);
//						}
//					}
//					List<ZrkQzOrder> orderList = null;
//					if(mesIdList!=null&&mesIdList.size()>0) {
//						orderList = zrkQzOrderService.listByIds(mesIdList);
//					}
//					if(orderList!=null&&orderList.size()>0) {
//						for(ZrkQzOrder zrkQzOrder:orderList) {
//							String userId = zrkQzOrder.getOperatorUsers();
//							if(oConvertUtils.isNotEmpty(userId)) {
//								String[] ids = userId.split(",");
//								if(ids!=null&&ids.length>0) {
//									for(String str:ids) {
//										userIdList.add(str);
//									}
//								}
//							}
//						}
//						String[] userids = userIdList.toArray(new String[userIdList.size()]);
//						List<LoginUser> loginUserList = null;
//						if(userids!=null&&userids.length>0) {
//							loginUserList = sysBaseAPI.queryAllUserByIds(userids);
//						}
//						if(loginUserList!=null&&loginUserList.size()>0) {
//							for(LoginUser loginUser:loginUserList) {
//								userSet.add(loginUser.getWorkNo());
//							}
//						}
//						String no = "";
//						for(String workNo:userSet) {
//							no = no+workNo+",";
//						}
//						if(oConvertUtils.isNotEmpty(no)) {
//							no = no.substring(0,no.length()-1);
//							tpb.setCz(no);
//						}
//					}
//				}
//				if(set!=null&&set.size()>0) {
//					for(String categoryId:set) {
//						List<SpecsAndCount> specsList = Lists.newArrayList();
//						if(sacList!=null&&sacList.size()>0) {
//							for(SpecsAndCount sac:sacList) {
//								BasMaterial basMaterial=basMaterialService.getById(sac.getCount());
//								if(basMaterial!=null) {
//									if(StringUtils.equals(categoryId, basMaterial.getCategoryId())) {
//										BigDecimal width = basMaterial.getWidth();
//										if(oConvertUtils.isEmpty(width)) {
//											width = BigDecimal.ZERO;
//										}
//										BigDecimal length = basMaterial.getLength();
//										if(oConvertUtils.isEmpty(length)) {
//											length = BigDecimal.ZERO;
//										}
//										specs = width.setScale(2, BigDecimal.ROUND_HALF_UP)+"*"+length.setScale(2, BigDecimal.ROUND_HALF_UP);
//										SpecsAndCount c = new SpecsAndCount();
//										c.setCount(sac.getCount());
//										c.setSpecs(specs);
//										specsList.add(c);
//									}
//								}
//							}
//						}
//						specsListMap.put(categoryId, specsList);
//					}
//				}
//				List<ProductDetails> pdList=new ArrayList<ProductDetails>();
//				for(String str:specsListMap.keySet()) {
//					Map<String,Integer> map = new HashMap<String,Integer>();
//					BasMaterialCategory basMaterial=basMaterialCategoryService.getById(str);
//					ProductDetails pd=new ProductDetails();
//					if(basMaterial!=null) {
//						pd.setProductName(basMaterial.getName());
//					}
//					List<SpecsAndCount> scList = Lists.newArrayList();
//					for(SpecsAndCount sac:specsListMap.get(str)) {
//						if(sac!=null) {
//							//计数器，用来记录数据的个数
//						    Integer i = 1;
//						    if(map.get(sac.getSpecs()) != null){
//						        i=map.get(sac.getSpecs())+1;
//						    }
//						    map.put(sac.getSpecs(),i);
//						}
//					}
//					for(String s:map.keySet()) {
//						SpecsAndCount sc = new SpecsAndCount();
//						sc.setSpecs(s);
//						sc.setCount(map.get(s).toString());
//						for(SpecsAndCount sac:specsListMap.get(str)) {
//							BasMaterial material=basMaterialService.getById(sac.getCount());
//							BasMaterialTemp basMaterialTemp = basMaterialTempService.getByCode(material.getCode());
//							if(basMaterialTemp!=null) {
//								if(StringUtils.equals(basMaterialTemp.getProcedureId(), MaterialConstant.PROCESS_CUTTING_BIG)||
//										StringUtils.equals(basMaterialTemp.getProcedureId(), MaterialConstant.PROCESS_CUTTING_NORMAL)) {
//									if(oConvertUtils.isNotEmpty(material.getViceQuantity())) {
//										BigDecimal vq = material.getViceQuantity();
//										if(oConvertUtils.isEmpty(vq)) {
//											vq = BigDecimal.ZERO;
//										}
//										sc.setCount(vq.setScale(2, BigDecimal.ROUND_HALF_UP)+"*"+map.get(s).toString());
//									}
//								}
//							}
//						}
//						scList.add(sc);
//					}
//					pd.setScList(scList);
//					pdList.add(pd);
//				}
//				tpb.setPdList(pdList);
//			}
//			tpb.setCount(count.toString());
//			QueryWrapper<StkIoBill> qwSib=new QueryWrapper<StkIoBill>();
//			qwSib.eq("bill_no", zd.getBillNo());
//			StkIoBill sib=stkIoBillService.getOne(qwSib.last("LIMIT 1"));
//			if(null!=sib) {
				
//			}
//			tpb.setDirection("");
//			String operators="";
//			//生产人员
//			List<StkTrayDetail> detailList = this.stkTrayDetailServie.selectByMainId(id);
//			if(CollUtil.isNotEmpty(detailList)) {
//				List<String> codeList = Lists.newArrayList();
//				for (StkTrayDetail detail : detailList) {
//					String materialCode = detail.getMaterialCode();
//					codeList.add(materialCode);
//				}
//				List<BasMaterialTemp> materialTempList = basMaterialTempService.getByCodes(codeList);
//				if(CollUtil.isNotEmpty(materialTempList)) {
//					List<String> inspectors = Lists.newArrayList();
//					for (BasMaterialTemp temp : materialTempList) {
//						String inspector = temp.getInspector();
//						if(StringUtils.isBlank(inspector)) {
//							continue;
//						}
//						String[] strings = StringUtils.split(inspector, ",");
//						for(String str : strings) {
//							
//						}
//					}
//					
//					if(0 != inspectors.size()) {
//						operators = CollUtil.join(inspectors, ",");
//					}
//				}
//			}
//			//查询生产该产品的操作员(根据销售出库单查询)
//			String orderCode;
//			
//			try {
//				orderCode = sib.getSourceNo();
//			} catch (Exception e) {
//				orderCode="";
//			}
//			//查询生产工单
//			QueryWrapper<ZzShoporder> qw=new QueryWrapper<ZzShoporder>();
//			qw.eq("order_no",orderCode);
//			List<ZzShoporder> zsList=zzShoporderService.list(qw);
//			if(null!=zsList&&zsList.size()>0) {
//				for(ZzShoporder so:zsList) {
//					//查询工序操作人
//					QueryWrapper<ZrkOrderProcess> qwzop=new QueryWrapper<ZrkOrderProcess>();
//					qwzop.eq("order_id", so.getId());
//					List<ZrkOrderProcess> zopList=zrkOrderProcessService.list(qwzop);
//					if(null!=zopList&&zopList.size()>0) {
//						for(ZrkOrderProcess zop:zopList) {
//							if(operators.equals("")) {
//								operators=zop.getUserId();
//							}else {
//								operators+=","+zop.getUserId();
//							}
//						}
//					}
//				}
//			}
//			if(!operators.equals("")) {
//				tpb.setOperators(operators);
//			}else {
//				//生成2个操作员
//				Random r = new Random();
//				int res1=r.nextInt(200)+20;
//				int res2=r.nextInt(200)+21;
//				if(res1==res2) {
//					res2=r.nextInt(200)+21;
//				}
//				operators=res1+","+res2;
//				tpb.setOperators(operators);
//			}
//			tpb.setSpecs(specs);
			//构造质检员随机数字1-200
//			Random r = new Random();
//			int re=r.nextInt(200)+20;
//			tpb.setZj(re+"");//质检员随机数
//			tpb.setZjResult("合格");
//			tpb.setMaterialName(materialName);
			result.setResult(tpb);
			return result;
		}
		
		
		
		
		
		
		
		//查询出货单信息
//		ZrkDeliver zd=zrkDeliverService.getById(id);
//		TPBean tpb=new TPBean();
//		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
//		tpb.setZdr(sysUser.getUsername());
//		List<CKBill> ckList=new ArrayList<CKBill>();
//		//获取托盘编号
//		String tp=null;
//		if(zd !=null && StringUtils.isNotBlank(zd.getStkTrayId())){
//			tp=zd.getStkTrayId();
//		}
//		//存在多个时以,分割
//		if(null!=tp&&!tp.equals("")) {
//			String [] trayIds=tp.split(",");
//			String materialName="";
//			BigDecimal count=BigDecimal.ZERO;
//			String specs="";
//			for(int i=0;i<trayIds.length;i++) {
//				//查询托盘明细
//				QueryWrapper<StkTrayDetail> queryWrapper=new QueryWrapper<StkTrayDetail>();
//				queryWrapper.eq("tray_id", trayIds[i]);
//				List<StkTrayDetail> stdList=stkTrayDetailServie.list(queryWrapper);
//				if(null!=stdList&&stdList.size()>0) {
//					for(StkTrayDetail st:stdList) {
//						//查询物料明细
//						BasMaterial basMaterial=basMaterialService.getById(st.getMaterialId());
//						CKBill ck=new CKBill();
//						ck.setProductName(basMaterial.getName());
//						ck.setRemark(basMaterial.getRemark());
//						ck.setSpecs(basMaterial.getWidth()+"*"+basMaterial.getLength());
//						ck.setCount(new BigDecimal("1"));
//						ckList.add(ck);
//						materialName=basMaterial.getName();
//						count=count.add(new BigDecimal("1"));//统计物料数量
//						//规格只记录一次
//						if(specs.equals("")) {
//							specs=basMaterial.getWidth()+"*"+basMaterial.getLength();
//						}
//					}
//					tpb.setCkList(ckList);
//				}
//			}
//			tpb.setCreateTime(zd.getCreateTime());
//			tpb.setCount(count);
//			//查询客户信息
//			QueryWrapper<StkIoBill> qwSib=new QueryWrapper<StkIoBill>();
//			qwSib.eq("bill_no", zd.getBillNo());
//			StkIoBill sib=stkIoBillService.getOne(qwSib.last("LIMIT 1"));
//			if(null!=sib) {
//				BasCustomer cus=null;
//				try {
//					cus = basCustomerService.getById(sib.getCustomerId());
//				} catch (Exception e) {
//					
//				}
//				if(null!=cus) {
//					tpb.setCustomerName(cus.getName());
//				}else {
//					tpb.setCustomerName("");
//				}
//			}else {
//				return Result.error("未查询到销售订单信息");
//			}
//			tpb.setDirection("");
//			String operators="";
//			//查询生产该产品的操作员(根据销售出库单查询)
//			String orderCode;
//			try {
//				orderCode = sib.getSourceNo();
//			} catch (Exception e) {
//				orderCode="";
//			}
//			//查询生产工单
//			QueryWrapper<ZzShoporder> qw=new QueryWrapper<ZzShoporder>();
//			qw.eq("order_no",orderCode);
//			List<ZzShoporder> zsList=zzShoporderService.list(qw);
//			if(null!=zsList&&zsList.size()>0) {
//				for(ZzShoporder so:zsList) {
//					//查询工序操作人
//					QueryWrapper<ZrkOrderProcess> qwzop=new QueryWrapper<ZrkOrderProcess>();
//					qwzop.eq("order_id", so.getId());
//					List<ZrkOrderProcess> zopList=zrkOrderProcessService.list(qwzop);
//					if(null!=zopList&&zopList.size()>0) {
//						for(ZrkOrderProcess zop:zopList) {
//							if(operators.equals("")) {
//								operators=zop.getUserId();
//							}else {
//								operators+=","+zop.getUserId();
//							}
//						}
//					}
//				}
//			}
//			if(!operators.equals("")) {
//				tpb.setOperators(operators);
//			}else {
//				//生成2个操作员
//				Random r = new Random();
//				int res1=r.nextInt(200)+20;
//				int res2=r.nextInt(200)+21;
//				if(res1==res2) {
//					res2=r.nextInt(200)+21;
//				}
//				operators=res1+","+res2;
//				tpb.setOperators(operators);
//			}
//			tpb.setSpecs(specs);
//			//构造质检员随机数字1-200
//			Random r = new Random();
//			int result=r.nextInt(200)+20;
//			tpb.setZj(result+"");//质检员随机数
//			tpb.setZjResult("合格");
//			tpb.setMaterialName(materialName);
//		}else {
//			return Result.error("未找到托盘数据");
//		}
//		return Result.ok(tpb);
		result.error500("失败");
		return result;
	}

}
